package com.foxconn.ipebg.common.base.listener;

import ipebg.mzk.facade.system.service.MsAccessCountRecordService;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;


public class WebVisitCountListener implements HttpSessionListener{
	private static Log log = LogFactory.getLog(WebVisitCountListener.class);

	/**
	 * 通过WebApplicationContextUtils 得到Spring容器的实例。根据bean的名称返回bean的实例。
	 * @param servletContext  ：ServletContext上下文。
	 * @param beanName  :要取得的Spring容器中Bean的名称。
	 * @return 返回Bean的实例。
	 */
	private Object getObjectFromApplication(ServletContext servletContext,String beanName){
		//通过WebApplicationContextUtils 得到Spring容器的实例。
		ApplicationContext application=WebApplicationContextUtils.getWebApplicationContext(servletContext);
		//返回Bean的实例。
		return application.getBean(beanName);
	}
	
	@Override
	public void sessionCreated(HttpSessionEvent event) {
		 HttpSession session = event.getSession();
		 try {
			//通过抽象的私有方法得到Spring容器中Bean的实例。
			 MsAccessCountRecordService msAccessCountRecordServiceImpl=(MsAccessCountRecordService)this.getObjectFromApplication(session.getServletContext(), "msAccessCountRecordServiceImpl");
			 log.info("Record sessionId:"+session.getId());
			 msAccessCountRecordServiceImpl.AddVisitUser(session.getId());
			 
		} catch (Exception e) {
			log.error(e.getMessage());
		}
	     //ServletContext application = session.getServletContext();
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent event) {
		HttpSession session = event.getSession();
		 try {
			//通过抽象的私有方法得到Spring容器中Bean的实例。
			 MsAccessCountRecordService msAccessCountRecordServiceImpl=(MsAccessCountRecordService)this.getObjectFromApplication(session.getServletContext(), "msAccessCountRecordServiceImpl");
			 log.info("Remove sessionId:"+session.getId());
			 msAccessCountRecordServiceImpl.RemoveVisitUser(session.getId());//AddVisitUser(session.getId());			 
		} catch (Exception e) {
			log.error(e.getMessage());
		}
	}

}
